﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using Abp.Linq.Extensions;
using Abp.UI;
using SingleUserMall.Article.Form;
using SingleUserMall.Article.VO;
using SingleUserMall.Common;

namespace SingleUserMall.Article
{
    public class ArticlesManageAppService : SingleUserMallAppServiceBase, IArticlesManageAppService
    {
        private readonly IRepository<Articles, long> _articlesRepository;
        public ArticlesManageAppService(IRepository<Articles, long> articlesRepository)
        {
            _articlesRepository = articlesRepository;

        }

        public async Task<PagedResultDto<ArticlesVO>> GetAllArticlesAsync(ArticlesSearchForm form)
        {
            var query = _articlesRepository.GetAll()
               .WhereIf(!string.IsNullOrEmpty(form.Keywords), x => x.Title.Contains(form.Keywords) && x.Content.Contains(form.Keywords))
               .WhereIf(form.ArticleType.HasValue, x => x.ArticleType == form.ArticleType)
               .OrderByDescending(x => x.CreationTime);
            return await query.ToPagedResultDtoAsync<Articles, ArticlesVO>(form, (c, vo) => {
                vo.CreationTime = c.CreationTime;
                
            });
        }

        public async Task SaveArticlesAsync(ArticlesForm form)
        {
            try
            {
                var articles = await _articlesRepository.FirstOrDefaultAsync(x => x.Id == form.Id);
                if (articles != null)
                {
                    articles = form.MapTo(articles);
                    articles.ArticleType = form.ArticleType;
                    articles.Picture = form.Picture;
                    articles.Content = form.Content;
                    await _articlesRepository.UpdateAsync(articles);
                }
                else
                {
                    articles = form.MapTo<Articles>();
                    articles.ArticleType = form.ArticleType;
                    articles.Picture = form.Picture;
                    articles.Content = form.Content;
                    await _articlesRepository.InsertAsync(articles);

                }
                await CurrentUnitOfWork.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                throw new UserFriendlyException(ex.Message);
            }
        }
        public async Task  DeleteArticlesAsync(SingleId<long> form)
        {
            await _articlesRepository.DeleteAsync(x => x.Id == form.Id);
         
        }
    }
}
